package dyyx.util;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;

public abstract class EsClientUtils {
	
	//private static final DefaultHttpClient client = new DefaultHttpClient();
	
	private static CloseableHttpClient httpClient;
	private static PoolingHttpClientConnectionManager cm;
	
	
	
	private static final String METHOD_GET = "GET";
	private static final String METHOD_POST = "POST";
	private static final String METHOD_PUT = "PUT";
	private static final String METHOD_DELETE = "DELETE";

	private static final Set<String> METHODS = new HashSet<String>();
	
	static{
		METHODS.add(METHOD_GET);
		METHODS.add(METHOD_POST);
		METHODS.add(METHOD_PUT);
		METHODS.add(METHOD_DELETE);
		
		try {
			init();
		} catch (Throwable e) {
			throw new RuntimeException("EsClientUtils init error", e);
		}

	}
	
	private static void init() throws Exception {
		PoolingHttpClientConnectionManager cmTmp = new PoolingHttpClientConnectionManager();
		// Increase max total connection to 200
		cmTmp.setMaxTotal(3000);
		// Increase default max connection per route to 100
		cmTmp.setDefaultMaxPerRoute(1000);
		// Increase max connections for localhost:80 to 50
		// HttpHost localhost = new HttpHost("locahost", 80);
		// cm.setMaxPerRoute(new HttpRoute(localhost), 50);
	

		CloseableHttpClient httpClientTmp = HttpClients.custom().setConnectionManager(cmTmp).build();
		
		cm = cmTmp;
		httpClient = httpClientTmp;
	}

    //
	
	public static String doExecute(String url, String method, String requestBody,Map<String,String> headers) throws Exception {
		
		checkMethod(method);

		
		HttpUriRequest request = buildRequestInfo(url,method,requestBody);
		if(request==null){
			throw new Exception("request is null");
		}
		buildHeads(request,headers);
        
		
		HttpResponse res = httpClient.execute(request);
		StatusLine statusLine = res.getStatusLine();
		int statusCode = statusLine.getStatusCode();
		/*
		if( statusCode != HttpStatus.SC_OK){
			throw new RuntimeException("statusCode error,"+statusLine.toString());	
		}
		*/
		HttpEntity entity = res.getEntity();
		// EntityUtils.toString(entity)
		// 20200922 
		String result = EntityUtils.toString(entity,CommUtil.UTF8);
		return result;

	}
	
	
	private static void checkMethod(String method){
		if(StringUtils.isBlank(method)){
			throw new RuntimeException("method is blank");
		}
		if(!METHODS.contains(method)){
			throw new RuntimeException("method error,"+method);
		}
	}
	
	
	private static void buildHeads(HttpUriRequest request,Map<String,String> headers){
		if(request==null || headers==null || headers.isEmpty()){
			return;
		}
		Set<Map.Entry<String, String>> es = headers.entrySet();
		for(Map.Entry<String, String> item:es){
			request.setHeader(item.getKey(), item.getValue());
		}
	}
	
	
	private static HttpUriRequest buildRequestInfo(String url, String method, String requestBody)throws Exception{
		if(METHOD_POST.equals(method)){
			HttpPost request = new HttpPost(url);		
			if(!StringUtils.isBlank(requestBody)){
				// new StringEntity(requestBody.toString())
				// 20200922 中文分词 bugfix
				StringEntity s = new StringEntity(requestBody.toString(),ContentType.APPLICATION_JSON);
				// s.setContentEncoding("UTF-8");
				// s.setContentType("application/json");		
				request.setEntity(s);
			}	
			return request;
		}
		if(METHOD_PUT.equals(method)){
			HttpPut request = new HttpPut(url);		
			if(!StringUtils.isBlank(requestBody)){
				StringEntity s = new StringEntity(requestBody.toString(),ContentType.APPLICATION_JSON);
				// s.setContentEncoding("UTF-8");
				// s.setContentType("application/json");		
				request.setEntity(s);
			}	
			return request;
		}
		
		if(METHOD_GET.equals(method)){
			HttpGet request = new HttpGet(url);		
			
			return request;
		}
		
		
		if(METHOD_DELETE.equals(method)){
			HttpDelete request = new HttpDelete(url);		
			
			return request;
		}
		
		return null;
	}

}